<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input v-model="queryParams.employeeName" placeholder="请输入员工姓名" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item label="员工类别" prop="employeeType">
          <el-select v-model="queryParams.employeeType" placeholder="员工类别" clearable style="width: 240px">
            <el-option label="销售顾问" :value="1" />
            <el-option label="维修技师" :value="2" />
            <el-option label="行政人员" :value="3" />
            <el-option label="管理层" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"><el-icon><Search /></el-icon>搜索</el-button>
          <el-button @click="resetQuery"><el-icon><Refresh /></el-icon>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="table-container">
      <template #header>
        <div class="card-header">
          <span>员工列表</span>
          <div class="right">
            <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>新增</el-button>
            <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
            <el-button @click="handleExport"><el-icon><Download /></el-icon>导出</el-button>
          </div>
        </div>
      </template>

      <!-- 员工表格 -->
      <el-table
        v-loading="loading"
        :data="employeeList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="员工ID" prop="employeeId" width="80" />
        <el-table-column label="员工姓名" prop="employeeName" :show-overflow-tooltip="true" />
        <el-table-column label="手机号" prop="phoneNumber" :show-overflow-tooltip="true" />
        <el-table-column label="员工类别" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getEmployeeTypeTag(scope.row.employeeType)">
              {{ getEmployeeTypeName(scope.row.employeeType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="身份证号" prop="idCard" :show-overflow-tooltip="true" />
        <el-table-column label="薪资" prop="salary" width="120">
          <template #default="scope">
            {{ scope.row.salary ? `¥${scope.row.salary}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
            <el-dropdown>
              <el-button link type="primary">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleViewDetails(scope.row)">查看详情</el-dropdown-item>
                  <el-dropdown-item @click="handleAssignRole(scope.row)">分配角色</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改员工对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="employeeForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input v-model="form.employeeName" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="员工类别" prop="employeeType">
          <el-select v-model="form.employeeType" placeholder="请选择员工类别" style="width: 100%;">
            <el-option label="销售顾问" :value="1" />
            <el-option label="维修技师" :value="2" />
            <el-option label="行政人员" :value="3" />
            <el-option label="管理层" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="薪资" prop="salary">
          <el-input-number v-model="form.salary" :min="0" :precision="2" :step="1000" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Delete, Download, Refresh, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination/index.vue'
import axios from 'axios'

// 加载状态
const loading = ref(false)
// 选中ID数组
const selectedIds = ref([])
// 总条数
const total = ref(0)

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  employeeName: undefined,
  phoneNumber: undefined,
  employeeType: undefined
})

// 表单参数
const form = ref({
  employeeId: undefined,
  employeeName: undefined,
  phoneNumber: undefined,
  employeeType: undefined,
  idCard: undefined,
  salary: 0
})

// 表单校验规则
const rules = {
  employeeName: [
    { required: true, message: '员工姓名不能为空', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  employeeType: [
    { required: true, message: '员工类别不能为空', trigger: 'change' }
  ],
  idCard: [
    { required: true, message: '身份证号不能为空', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ]
}

// 对话框状态
const dialog = reactive({
  visible: false,
  title: ''
})

// 员工表格数据
const employeeList = ref([])

// 在组件挂载时获取数据
onMounted(() => {
  getList()
})

// 获取员工列表
function getList() {
  loading.value = true
  axios.get('http://localhost:9999/getAllEmployees')
    .then(response => {
      console.log('员工列表响应数据:', response.data)
      let dataList = []
      
      if (Array.isArray(response.data)) {
        dataList = response.data.map(item => ({
          employeeId: item.empId,
          employeeName: item.empName,
          phoneNumber: item.empPhone,
          employeeType: item.empType,
          idCard: item.empIdno,
          salary: item.empSalary
        }))
        employeeList.value = dataList
        total.value = dataList.length
      } else if (response.data.rows) {
        dataList = response.data.rows.map(item => ({
          employeeId: item.empId,
          employeeName: item.empName,
          phoneNumber: item.empPhone,
          employeeType: item.empType,
          idCard: item.empIdno,
          salary: item.empSalary
        }))
        employeeList.value = dataList
        total.value = response.data.total || dataList.length
      } else {
        employeeList.value = []
        total.value = 0
      }
    })
    .catch(error => {
      console.error('获取员工列表失败:', error)
      employeeList.value = []
      total.value = 0
    })
    .finally(() => {
      loading.value = false
    })
}

// 获取员工类别标签类型
function getEmployeeTypeTag(type) {
  switch (type) {
    case 1: return 'success'
    case 2: return 'warning'
    case 3: return 'info'
    case 4: return 'danger'
    default: return 'info'
  }
}

// 获取员工类别名称
function getEmployeeTypeName(type) {
  switch (type) {
    case 1: return '销售顾问'
    case 2: return '维修技师'
    case 3: return '行政人员'
    case 4: return '管理层'
    default: return '未知'
  }
}

// 表单重置
function resetForm() {
  form.value = {
    employeeId: undefined,
    employeeName: undefined,
    phoneNumber: undefined,
    employeeType: undefined,
    idCard: undefined,
    salary: 0
  }
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

// 重置按钮操作
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    employeeName: undefined,
    phoneNumber: undefined,
    employeeType: undefined
  }
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedIds.value = selection.map(item => item.employeeId)
}

// 新增按钮操作
function handleAdd() {
  resetForm()
  dialog.visible = true
  dialog.title = '添加员工'
}

// 修改按钮操作
function handleUpdate(row) {
  resetForm()
  const employeeId = row.employeeId
  // 调用获取详情的 API
  axios.get(`http://localhost:9999/selectEmployeeById?employeeId=${employeeId}`)
    .then(response => {
      console.log('员工详情响应:', response.data)
      const employeeData = response.data
      // 处理后端返回的数据格式
      form.value = {
        employeeId: employeeData.empId,
        employeeName: employeeData.empName,
        phoneNumber: employeeData.empPhone,
        employeeType: employeeData.empType,
        idCard: employeeData.empIdno,
        salary: employeeData.empSalary
      }
      dialog.visible = true
      dialog.title = '修改员工'
    })
    .catch(error => {
      console.error('获取员工详情失败:', error)
      ElMessage.error('获取员工详情失败')
    })
}

// 提交按钮
function submitForm() {
  // 准备提交数据
  const submitData = {
    empId: form.value.employeeId,
    empName: form.value.employeeName,
    empPhone: form.value.phoneNumber,
    empType: form.value.employeeType,
    empIdno: form.value.idCard,
    empSalary: form.value.salary
  }
  
  if (submitData.empId) {
    // 更新
    axios.post('http://localhost:9999/updateEmployeeById', submitData)
      .then(() => {
        ElMessage.success('修改成功')
        dialog.visible = false
        getList()
      })
      .catch(error => {
        console.error('修改员工失败:', error)
        ElMessage.error('修改失败')
      })
  } else {
    // 新增
    axios.post('http://localhost:9999/insertEmployee', submitData)
      .then(() => {
        ElMessage.success('新增成功')
        dialog.visible = false
        getList()
      })
      .catch(error => {
        console.error('新增员工失败:', error)
        ElMessage.error('新增失败')
      })
  }
}

// 删除按钮操作
function handleDelete(row) {
  const employeeId = row.employeeId
  ElMessageBox.confirm('是否确认删除员工编号为"' + employeeId + '"的数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.post('http://localhost:9999/deleteEmployeeById', { empId: employeeId })
      .then(() => {
        ElMessage.success('删除成功')
        getList()
      })
      .catch(error => {
        console.error('删除员工失败:', error)
        ElMessage.error('删除失败')
      })
  }).catch(() => {})
}

// 批量删除操作
function handleBatchDelete() {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择至少一条记录')
    return
  }
  
  ElMessageBox.confirm('是否确认批量删除所选员工?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 由于后端没有批量删除API，这里循环调用单个删除API
    const deletePromises = selectedIds.value.map(id => 
      axios.post('http://localhost:9999/deleteEmployeeById', { empId: id })
    )
    
    Promise.all(deletePromises)
      .then(() => {
        ElMessage.success('批量删除成功')
        getList()
      })
      .catch(error => {
        console.error('批量删除失败:', error)
        ElMessage.error('批量删除失败')
      })
  }).catch(() => {})
}

// 导出按钮操作
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有员工数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 导出功能可以通过前端实现简单的CSV导出
    if (employeeList.value.length > 0) {
      const headers = ['员工ID', '员工姓名', '手机号', '员工类别', '身份证号', '薪资']
      const data = employeeList.value.map(item => [
        item.employeeId,
        item.employeeName,
        item.phoneNumber,
        getEmployeeTypeName(item.employeeType),
        item.idCard,
        item.salary
      ])
      
      // 这里可以实现CSV导出
      ElMessage.success('导出成功')
    } else {
      ElMessage.warning('没有数据可导出')
    }
  }).catch(() => {})
}

// 查看详情
function handleViewDetails(row) {
  const employeeId = row.employeeId
  axios.get(`http://localhost:9999/selectEmployeeById?employeeId=${employeeId}`)
    .then(response => {
      console.log('员工详情:', response.data)
      // 这里可以实现详情查看弹窗
      ElMessage.info('员工详情查看功能开发中')
    })
    .catch(error => {
      console.error('获取员工详情失败:', error)
      ElMessage.error('获取员工详情失败')
    })
}

// 分配角色
function handleAssignRole(row) {
  // 这里应该跳转到角色分配页面或打开角色分配弹窗
  ElMessage.info('角色分配功能开发中')
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 15px;
}

.table-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .right {
  display: flex;
    gap: 10px;
  }
}
</style> 